﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using XfTechOAWeb.IService;
using Microsoft.AspNetCore.Mvc.Filters;
using XfTechOAWeb.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Security.Claims;
using Castle.Core.Internal;
using XfTechOAWeb.Infrastructure.RedisCache;

namespace XfTechOAWeb.ApiServer.Auth
{
    /// <summary>
    /// 授权处理（自定义策略授权）
    /// </summary>
    public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionAuthorizationRequirement>
    {
        private readonly IUserService _userService;
        private readonly ILogger<PermissionAuthorizationHandler> _logger;
        private readonly ICSRedisHelper _redisClient;


        /// <summary>
        /// 构造方法
        /// </summary>
        public PermissionAuthorizationHandler(IUserService userService,
                                              ILogger<PermissionAuthorizationHandler> logger,
                                              ICSRedisHelper redisClient)
        {
            this._userService = userService; //依赖注入
            _logger = logger;
            _redisClient = redisClient;
        }

        /// <summary>
        /// 处理授权条件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       PermissionAuthorizationRequirement requirement)
        {
            //判断登录用户是否为空
            //if(context.User != null)
            //{
            //    if (context.User.IsInRole("admin")) //如果是管理员，则不检查权限
            //    {
                    context.Succeed(requirement);
            //    }
            //    else
            //    {
            //        //获取用户主键
            //        var userIdClaim = context.User.FindFirst(s => s.Type == ClaimTypes.NameIdentifier);
            //        int userId;
            //        if (!int.TryParse(userIdClaim.Value, out userId)) //获取用户主键
            //        {
            //            return Task.CompletedTask;
            //        }

            //        //先从redis中获取
            //        var key = $"userId_{userId}_permissions";
            //        //查询redis是否存入信息
            //        List<Permission> permissions = new();
            //        permissions = _redisClient.Get<List<Permission>>(key);
            //        if (permissions == null)
            //        {
            //            //如果redis中没有，则查询数据库
            //            permissions = _userService.GetUserPermissions(userId);
            //            _redisClient.Set(key, permissions, 30 * 60); //缓存60分钟
            //        }

            //        string requestUrl = requirement.Path.TrimEnd('/').ToLower(); //获取请求的api路径
            //        if (permissions.Select(x => x.PApiUrl?.ToLower()).Contains(requestUrl))
            //        {
            //            context.Succeed(requirement);
            //        }
            //        else
            //        {
            //            _logger.LogWarning("用户试图访问没有被授权的Api接口");
            //        }
            //    }
            //}

            return Task.CompletedTask;
        }
    }
}
